<template>
    <div style="width: 100%; height: 64vh; display: flex; flex-direction: column">
        <!-- 新增按钮 -->
        <div
                style="
        width: 100%;
        display: flex;
        height: 40px;
        justify-content: space-between;
        align-items: center;
      "
        >
            <h4>上报协议列表</h4>
            <el-button :icon="Plus" type="primary" @click="openDialog(`add`)"
            >新增上报协议
            </el-button
            >
        </div>

        <!-- 表格 -->
        <div style="flex: 1">
            <!-- 设置间距为20像素 -->
            <el-row :gutter="20">
                <el-col
                        :xs="24"
                        :sm="24"
                        :md="24"
                        :lg="12"
                        v-for="item in dataHandler.data"
                        :key="item"
                >
                    <el-card shadow="hover" style="margin-bottom: 10px">
                        <div style="width: 100%; display: flex; justify-content: end">
                            <!-- @vue-ignore -->
                            <el-icon
                                    :size="20"
                                    style="
                  justify-content: right;
                  cursor: pointer;
                  transition: transform 0.3s;
                "
                                    @click="openDialog(`edit`, item)"
                                    @mouseenter="
                  (event) => (event.target.style.transform = 'scale(1.4)')
                "
                                    @mouseleave="
                  (event) => (event.target.style.transform = 'scale(1)')
                "
                            >
                                <View/>
                            </el-icon>

                            <!-- @vue-ignore -->
                            <el-popconfirm
                                    confirm-button-text="确定"
                                    cancel-button-text="取消"
                                    :icon="Delete"
                                    width="200px"
                                    icon-color="#FF0000"
                                    :title="`确定要删除--${item.remark}--处理器吗?`"
                                    @confirm="deleteDataHandler(item.id!)"
                            >
                                <template #reference>
                                    <!-- @vue-ignore -->
                                    <el-icon
                                            :size="20"
                                            style="
                      justify-content: right;
                      cursor: pointer;
                      margin-left: 10px;
                      transition: transform 0.3s;
                    "
                                            @mouseenter="
                      (event) => (event.target.style.transform = 'scale(1.4)')
                    "
                                            @mouseleave="
                      (event) => (event.target.style.transform = 'scale(1)')
                    "
                                    >
                                        <Delete/>
                                    </el-icon>
                                </template>
                            </el-popconfirm>
                        </div>
                        <div style="display: flex; justify-content: space-between">
                            <div style="display: flex; margin-right: 10px">
                                <el-tag
                                        :style="{ marginRight: '6px' }"
                                        :type="item.status ? 'success' : 'info'"
                                >{{ item.status ? "开启" : "关闭" }}
                                </el-tag
                                >
                                <span>{{ "名称: " + item.name }}</span>
                            </div>

                            <span style="margin-left: 50px">
                更新时间: {{ item.updatedAt.split(".")[0] }}
              </span>
                        </div>
                        <div
                                style="
                margin-top: 10px;
                display: flex;
                justify-content: space-between;
              "
                        >
                            <div style="display: flex">
                                <span v-if="item.dataHandlerNetWay == 1"> HTTP </span>
                                <span v-if="item.dataHandlerNetWay == 2"> MQTT </span>
                                <span v-if="item.dataHandlerNetWay == 3"> TCP </span>
                                <div style="margin-left: 20px">
                  <span v-if="item.dataHandlerNetWay == 1">
                    {{ item.httpDataUrl }}</span
                  >
                                    <span v-if="item.dataHandlerNetWay == 2">
                    {{ item.mqttUrl }}
                  </span>
                                    <span v-if="item.dataHandlerNetWay == 3">
                    {{ item.tcpDataIp + item.tcpDataPort }}
                  </span>
                                </div>
                            </div>

                            <div>创建时间: {{ item.createdAt.split(".")[0] }}</div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <el-pagination
                style="justify-content: right"
                v-model:current-page="handlerListDTO.pageNum"
                v-model:page-size="handlerListDTO.pageSize"
                :size="'default'"
                :background="handlerListDTO"
                layout="total, prev, pager, next, jumper"
                :total="dataHandler.total"
                @current-change="getDataHandler"
        />
    </div>

    <el-dialog
            v-model="dialog.show"
            draggable
            class="myFrom"
            width="60vw"
            style="display: flex; flex-direction: column"
    >
        <template #header>
            <div
                    style="
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        "
            >
                <h3
                        style="
            width: 200px;
            text-align: center;
            margin: 0;
            border: 0;
            padding: 0;
          "
                >
                    {{ dialog.title }}
                </h3>
                <el-icon style="cursor: pointer" @click="testFlag = !testFlag">
                    <Switch/>
                </el-icon>
            </div>
        </template>
        <el-scrollbar v-if="!testFlag" height="55vh">
            <el-form :model="dialog.form" label-width="120px" ref="dialogForm">
                <el-form-item label="上报名称" prop="name">
                    <el-input
                            v-model="dialog.form.name"
                            placeholder="请输入上报名称（填写项目名称）"
                    ></el-input>
                </el-form-item>
                <el-form-item v-if="isShowTempSelect" label="协议选择" prop="status">
                    <el-select
                            v-model="tempSelectValue"
                            placeholder="请选择协议类型"
                            @change="tempChange"
                    >
                        <el-option v-for="(item,i) in tempList" :key="i" :label="item.name" :value="item"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch
                            v-model="dialog.form.status"
                            :active-text="'开启'"
                            :inactive-text="'关闭'"
                    ></el-switch>
                </el-form-item>

                <el-form-item label="协议代码" prop="dataHandlerCode">
                    <v-ace-editor
                            v-model:value="dialog.form.dataHandlerCode!"
                            style="
              width: 100%;
              height: 40vh;
              font-size: 16px;
              border: 1px solid;
            "
                            placeholder="请输入处理器代码"
                            lang="javascript"
                            theme="monokai"
                            :options="options"
                    />
                </el-form-item>
                <el-form-item label="处理方式" prop="dataHandlerNetWay">
                    <el-select
                            v-model="dialog.form.dataHandlerNetWay"
                            placeholder="请选择处理方式"
                    >
                        <el-option label="HTTP" :value="1"/>
                        <el-option label="MQTT" :value="2"/>
                        <el-option label="TCP" :value="3"/>
                        <el-option
                                :disabled="true"
                                label="FTP"
                                :value="4"
                        />
                        <el-option
                                :disabled="true"
                                label="RabbitMq"
                                :value="5"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="处理器类型" prop="dataHandlerType">
                    <el-select
                            v-model="dialog.form.dataHandlerType"
                            placeholder="请选择处理器类型"
                    >
                        <el-option label="中置(数据收集)" :value="2"/>
                        <el-option label="前置" :value="1"/>
                        <el-option label="后置" :value="3"/>
                    </el-select>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 2"
                        label="url"
                        prop="mqttUrl"
                >
                    <el-input
                            v-model="dialog.form.mqttUrl"
                            placeholder="请输入MQTT URL"
                    ></el-input>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 2"
                        label="主题"
                        prop="mqttTopic"
                >
                    <el-input
                            v-model="dialog.form.mqttTopic"
                            placeholder="请输入MQTT主题"
                    ></el-input>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 2"
                        label="用户名"
                        prop="mqttUserName"
                >
                    <el-input
                            v-model.trim="dialog.form.mqttUserName"
                            placeholder="请输入MQTT用户名"
                    ></el-input>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 2"
                        label="密码"
                        prop="mqttPassword"
                >
                    <el-input
                            type="password"
                            v-model.trim="dialog.form.mqttPassword"
                            placeholder="请输入MQTT密码"
                    ></el-input>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 2"
                        label="Qos"
                        prop="mqttQos"
                >
                    <el-select v-model="dialog.form.mqttQos" placeholder="请选择Qos">
                        <el-option label="QoS0" :value="0"/>
                        <el-option label="QoS1" :value="1"/>
                        <el-option label="QoS2" :value="2"/>
                    </el-select>
                </el-form-item>

                <!-- http -->
                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 1"
                        label="数据推送地址"
                        prop="httpDataUrl"
                >
                    <el-input
                            v-model="dialog.form.httpDataUrl"
                            placeholder="请输入url"
                    ></el-input>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 1"
                        label="推送方式"
                        prop="httpDataUrl"
                >
                    <el-select
                            v-model="dialog.form.httpDataWay"
                            placeholder="请选择推送方式"
                    >
                        <el-option label="get" :value="1"/>
                        <el-option label="post" :value="2"/>
                    </el-select>
                </el-form-item>
                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 1"
                        label="Token获取url"
                        prop="httpUrlTokenUrl"
                >
                    <el-input
                            v-model.trim="dialog.form.httpUrlTokenUrl"
                            placeholder="请输入url，没有不填"
                    ></el-input>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 1"
                        label="Token获取方式"
                        prop="httpUrlTokenWay"
                >
                    <el-select
                            v-model="dialog.form.httpUrlTokenWay"
                            placeholder="请选择请求方式，，没有不填"
                    >
                        <el-option label="get" :value="1"/>
                        <el-option label="post" :value="2"/>
                    </el-select>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 1"
                        label="Token请求参数"
                        prop="httpUrlTokenGetParams"
                >
                    <v-ace-editor
                            style="
              width: 100%;
              height: 20vh;
              font-size: 16px;
              border: 1px solid;
            "
                            placeholder="请输入token请求参数"
                            v-model:value="dialog.form.httpUrlTokenGetParams!"
                            lang="javascript"
                            theme="monokai"
                            :options="options"
                    />
                </el-form-item>


                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 3"
                        label="IP"
                        prop="tcpDataIp"
                >
                    <el-input
                            v-model="dialog.form.tcpDataIp"
                            placeholder="请输入TCP数据IP地址"
                    ></el-input>
                </el-form-item>

                <el-form-item
                        v-if="dialog.form.dataHandlerNetWay === 3"
                        label="端口"
                        prop="tcpDataPort"
                >
                    <el-input
                            v-model.number="dialog.form.tcpDataPort"
                            placeholder="请输入TCP数据端口"
                    ></el-input>
                </el-form-item>

                <el-form-item label="额外信息" prop="otherInfo">
                    <v-ace-editor
                            style="
              width: 100%;
              height: 20vh;
              font-size: 16px;
              border: 1px solid;
            "
                            v-model:value="dialog.form.otherInfo!"
                            lang="json"
                            placeholder="请输入额外信息"
                            theme="monokai"
                            :options="options"
                    />
                </el-form-item>

                
            </el-form>
        </el-scrollbar>

        <el-scrollbar v-else height="55vh">
            <h3>测试参数</h3>
            <v-ace-editor
                    v-model:value="handlerTestDTO.inputData"
                    style="width: 100%; height: 20vh; font-size: 16px; border: 1px solid"
                    placeholder="请输入测试参数"
                    lang="json"
                    theme="monokai"
                    :options="options"
            />
            <div
                    style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
            >
                <h3>响应结果</h3>
                <el-button type="primary" @click="handlerTest">发送</el-button>
            </div>
            <v-ace-editor
                    v-model:value="handlerTestResult"
                    style="width: 100%; height: 20vh; font-size: 16px; border: 1px solid"
                    placeholder="响应结果"
                    lang="json"
                    theme="monokai"
                    :options="options"
            />
        </el-scrollbar>
        <template #footer>
      <span v-if="!testFlag" class="dialog-footer">
        <el-button @click="dialog.show = false">取消</el-button>
        <el-button type="primary" @click="addOrEditDataHandler()">
          确定
        </el-button>
      </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    getDataHandlerAPI,
    addDataHandlerAPI,
    updateDataHandlerAPI,
    type DataHandler,
    type DataHandlerDTO,
    type HandlerListDTO,
    deleteDataHandlerAPI,
    type DebugDecoderParams,
    type HandlerDebugParams,
    dataHandlerDebugAPI,
} from "@/api/solutionService";
import type {CollectTask} from "@/model/group";
import {Plus, View, Delete, Switch} from "@element-plus/icons-vue";
import {ref, watch, reactive} from "vue";
import {VAceEditor} from "vue3-ace-editor";
import {Ace} from "ace-builds";
import {ElMessage} from "element-plus";
import {getListAPI} from "@/api/temp"

const options: Partial<Ace.EditorOptions> = reactive({
    useWorker: true, // 启用语法检查,必须为true
    enableBasicAutocompletion: true, // 自动补全
    enableLiveAutocompletion: true, // 智能补全
    enableSnippets: true, // 启用代码段
    showPrintMargin: false, // 去掉灰色的线，printMarginColumn
    highlightActiveLine: true, // 高亮行
    highlightSelectedWord: true, // 高亮选中的字符
    tabSize: 4, // tab锁进字符
    fontSize: 14, // 设置字号
    wrap: false, // 是否换行
    readonly: false, // 是否可编辑
    // minLines: 10, // 最小行数，minLines和maxLines同时设置之后，可以不用给editor再设置高度
    // maxLines: 50, // 最大行数
});

defineOptions({
    name: "DataHandlerView",
});

watch(
    () => dataHandlerData,
    () => {
        handlerListDTO.value.collectTaskId = dataHandlerData.id!;
        getDataHandler();
    }
);

const {data: dataHandlerData} = defineProps<{
    data: CollectTask;
}>();

/**
 * 数据处理器
 */
const dataHandler = ref<{
    data: DataHandler[];
    loading: boolean;
    total: number;
}>({
    data: [],
    loading: false,
    total: 0,
});

/**
 * 获取处理器参数
 */
const handlerListDTO = ref<HandlerListDTO>({
    collectTaskId: 0,
    pageNum: 1,
    pageSize: 10,
});

/**
 * 获取数据处理器列表
 */
async function getDataHandler() {
    dataHandler.value.loading = true;
    handlerListDTO.value.collectTaskId = dataHandlerData.id!;
    const {
        code,
        data: {total, list},
    } = await getDataHandlerAPI(handlerListDTO.value).finally(() => {
        dataHandler.value.loading = false;
    });
    if (code === 200) {
        dataHandler.value.data = list ?? new Array<DataHandler>();
        dataHandler.value.total = total;
    }
}

/**
 * 新增|编辑弹窗
 */
const dialog = ref<{
    title: string;
    show: boolean;
    loading: boolean;
    form: DataHandlerDTO | DataHandler;
}>({
    title: "新增上报协议",
    show: false,
    loading: false,
    form: {},
});

/**
 * 打开新增|编辑弹窗
 */

//解析器模板列表
const tempList = ref<any[]>([{code: "", name: "自定义"}])
const isShowTempSelect = ref(false)
//模板选择器展示
const tempSelectValue = ref("")

async function openDialog(type: "add" | "edit", data?: DataHandler) {
    dialog.value.title = type === "add" ? "新增上报协议" : "编辑上报协议";
    if (type === "add") {
        isShowTempSelect.value = true
        const res = await getListAPI({
            pageSize: 1000,
            pageNum: 1,
            type: 2,
        });
        if (res.data.list !== null) {
            tempList.value = tempList.value.concat(res.data.list);
        }
    } else {
        isShowTempSelect.value = false
    }
    dialog.value.show = true;
    dialog.value.form =
        type === "add"
            ? {
                collectTaskId: dataHandlerData.id!,
            }
            : {...data!};
}

/**
 * 新增|修改处理器
 */
async function addOrEditDataHandler() {
    dialog.value.loading = true;
    const fun =
        dialog.value.title === "新增上报协议"
            ? addDataHandlerAPI
            : updateDataHandlerAPI;
    // @ts-ignore
    const res = await fun({...dialog.value.form}).finally(() => {
        dialog.value.loading = false;
    });
    if (res.code === 200) {
        ElMessage.success(
            dialog.value.title === "新增上报协议" ? "新增成功" : "修改成功"
        );
    } else {
        ElMessage.warning(res.data);
        return;
    }
    getDataHandler();
    dialog.value.show = false;
}

/**
 * 删除处理器
 */
async function deleteDataHandler(id: number) {
    const res = await deleteDataHandlerAPI(id);
    if (res.code === 200) {
        ElMessage.success("删除成功");
        getDataHandler();
    }else {
        ElMessage.error(res.data);
    }

}

/**
 * 处理器测试参数
 */
const handlerTestDTO = ref<HandlerDebugParams>({
    handlerId: 0,
    inputData: "",
});

/**
 * 处理器测试响应结果
 *
 * */
const handlerTestResult = ref("");

/**
 * 处理器测试
 *
 */
async function handlerTest() {
    console.log("-------dialog.value.form-------", dialog.value.form)
    // @ts-ignore
    handlerTestDTO.value.handlerId = dialog.value.form.id;
    dataHandlerDebugAPI(handlerTestDTO.value).then((res) => {
        if (res.code === 200) {
            handlerTestResult.value = res.data;
        } else {
            handlerTestResult.value = res.data;
        }
    });
}

/**
 * 测试开关
 */
const testFlag = ref(false);

/**
 * 模板列表change事件
 */
function tempChange(val: string) {
    tempSelectValue.value = val.name
    console.log(val)
    //将val在form中有的属性合并
    dialog.value.form.dataHandlerCode = val.code
    dialog.value.form.dataHandlerNetWay = val.dataHandlerNetWay
    dialog.value.form.dataHandlerType = val.dataHandlerType
    dialog.value.form.otherInfo = val.otherInfo
    if (dialog.value.form.dataHandlerNetWay === 1) {

        dialog.value.form.httpUrlTokenUrl = val.httpUrlTokenUrl
        dialog.value.form.httpUrlTokenWay = val.httpUrlTokenWay
        dialog.value.form.httpUrlTokenGetParams = val.httpUrlTokenGetParams
        dialog.value.form.httpDataUrl = val.httpDataUrl
        dialog.value.form.httpDataWay = val.httpDataWay

    } else if (dialog.value.form.dataHandlerNetWay === 2) {

        dialog.value.form.mqttUrl = val.mqttUrl
        dialog.value.form.mqttTopic = val.mqttTopic
        dialog.value.form.mqttUserName = val.mqttUserName
        dialog.value.form.mqttPassword = val.mqttPassword
        dialog.value.form.mqttQos = val.mqttQos

    } else if (dialog.value.form.dataHandlerNetWay === 3) {

        dialog.value.form.tcpDataIp = val.tcpDataIp
        dialog.value.form.tcpDataPort = val.tcpDataPort

    }

}

</script>

<style scoped>
.myFrom {
    &::-webkit-scrollbar {
        width: 6px;
        height: 8px;
    }

    &::-webkit-scrollbar-button {
        display: none;
    }

    &::-webkit-scrollbar-thumb {
        background: rgba(144, 147, 153, 0.3);
        cursor: pointer;
        border-radius: 4px;
    }

    &::-webkit-scrollbar-corner {
        display: none;
    }

    &::-webkit-resizer {
        display: none;
    }
}
</style>
